{
  "cells": [
    {
      "cell_type": "raw",
      "id": "afaf8039",
      "metadata": {
        "vscode": {
          "languageId": "raw"
        }
      },
      "source": [
        "---\n",
        "sidebar_label: IBM watsonx.ai\n",
        "---"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "9a3d6f34",
      "metadata": {},
      "source": [
        "# IBM watsonx.ai\n",
        "\n",
        "\n",
        "This will help you get started with IBM watsonx.ai [embedding models](/docs/concepts/embedding_models) using LangChain. For detailed documentation on `IBM watsonx.ai` features and configuration options, please refer to the [API reference](https://api.js.langchain.com/modules/_langchain_community.embeddings_ibm.html).\n",
        "\n",
        "## Overview\n",
        "### Integration details\n",
        "\n",
        "\n",
        "| Class | Package | Local | [Py support](https://python.langchain.com/docs/integrations/text_embedding/ibm_watsonx/) | Package downloads | Package latest |\n",
        "| :--- | :--- | :---: | :---: |  :---: | :---: |\n",
        "| [`WatsonxEmbeddings`](https://api.js.langchain.com/classes/_langchain_community.embeddings_ibm.WatsonxEmbeddings.html) | [@langchain/community](https://www.npmjs.com/package/@langchain/community)| ❌ | ✅  | ![NPM - Downloads](https://img.shields.io/npm/dm/@langchain/community?style=flat-square&label=%20&) | ![NPM - Version](https://img.shields.io/npm/v/@langchain/community?style=flat-square&label=%20&) |\n",
        "\n",
        "## Setup\n",
        "\n",
        "To access IBM WatsonxAI embeddings you'll need to create an IBM watsonx.ai account, get an API key or any other type of credentials, and install the `@langchain/community` integration package.\n",
        "\n",
        "### Credentials\n",
        "\n",
        "\n",
        "Head to [IBM Cloud](https://cloud.ibm.com/login) to sign up to IBM watsonx.ai and generate an API key or provide any other authentication form as presented below.\n",
        "\n",
        "#### IAM authentication\n",
        "\n",
        "```bash\n",
        "export WATSONX_AI_AUTH_TYPE=iam\n",
        "export WATSONX_AI_APIKEY=<YOUR-APIKEY>\n",
        "```\n",
        "\n",
        "#### Bearer token authentication\n",
        "\n",
        "```bash\n",
        "export WATSONX_AI_AUTH_TYPE=bearertoken\n",
        "export WATSONX_AI_BEARER_TOKEN=<YOUR-BEARER-TOKEN>\n",
        "```\n",
        "\n",
        "#### IBM watsonx.ai software authentication\n",
        "\n",
        "```bash\n",
        "export WATSONX_AI_AUTH_TYPE=cp4d\n",
        "export WATSONX_AI_USERNAME=<YOUR_USERNAME>\n",
        "export WATSONX_AI_PASSWORD=<YOUR_PASSWORD>\n",
        "export WATSONX_AI_URL=<URL>\n",
        "```\n",
        "\n",
        "Once these are placed in your environment variables and object is initialized authentication will proceed automatically.\n",
        "\n",
        "Authentication can also be accomplished by passing these values as parameters to a new instance.\n",
        "\n",
        "## IAM authentication\n",
        "\n",
        "```typescript\n",
        "import { WatsonxEmbeddings } from \"@langchain/community/embeddings/ibm\";\n",
        "\n",
        "const props = {\n",
        "  version: \"YYYY-MM-DD\",\n",
        "  serviceUrl: \"<SERVICE_URL>\",\n",
        "  projectId: \"<PROJECT_ID>\",\n",
        "  watsonxAIAuthType: \"iam\",\n",
        "  watsonxAIApikey: \"<YOUR-APIKEY>\",\n",
        "};\n",
        "const instance = new WatsonxEmbeddings(props);\n",
        "```\n",
        "\n",
        "## Bearer token authentication\n",
        "\n",
        "```typescript\n",
        "import { WatsonxEmbeddings } from \"@langchain/community/embeddings/ibm\";\n",
        "\n",
        "const props = {\n",
        "  version: \"YYYY-MM-DD\",\n",
        "  serviceUrl: \"<SERVICE_URL>\",\n",
        "  projectId: \"<PROJECT_ID>\",\n",
        "  watsonxAIAuthType: \"bearertoken\",\n",
        "  watsonxAIBearerToken: \"<YOUR-BEARERTOKEN>\",\n",
        "};\n",
        "const instance = new WatsonxEmbeddings(props);\n",
        "```\n",
        "\n",
        "### IBM watsonx.ai software authentication\n",
        "\n",
        "```typescript\n",
        "import { WatsonxEmbeddings } from \"@langchain/community/embeddings/ibm\";\n",
        "\n",
        "const props = {\n",
        "  version: \"YYYY-MM-DD\",\n",
        "  serviceUrl: \"<SERVICE_URL>\",\n",
        "  projectId: \"<PROJECT_ID>\",\n",
        "  watsonxAIAuthType: \"cp4d\",\n",
        "  watsonxAIUsername: \"<YOUR-USERNAME>\",\n",
        "  watsonxAIPassword: \"<YOUR-PASSWORD>\",\n",
        "  watsonxAIUrl: \"<url>\",\n",
        "};\n",
        "const instance = new WatsonxEmbeddings(props);\n",
        "```\n",
        "\n",
        "If you want to get automated tracing of your model calls you can also set your [LangSmith](https://docs.smith.langchain.com/) API key by uncommenting below:\n",
        "\n",
        "```bash\n",
        "# export LANGSMITH_TRACING=\"true\"\n",
        "# export LANGSMITH_API_KEY=\"your-api-key\"\n",
        "```\n",
        "\n",
        "### Installation\n",
        "\n",
        "The LangChain IBM watsonx.ai integration lives in the `@langchain/community` package:\n",
        "\n",
        "```{=mdx}\n",
        "import IntegrationInstallTooltip from \"@mdx_components/integration_install_tooltip.mdx\";\n",
        "import Npm2Yarn from \"@theme/Npm2Yarn\";\n",
        "\n",
        "<IntegrationInstallTooltip></IntegrationInstallTooltip>\n",
        "\n",
        "<Npm2Yarn>\n",
        "  @langchain/community @langchain/core\n",
        "</Npm2Yarn>\n",
        "\n",
        "```"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "45dd1724",
      "metadata": {},
      "source": [
        "## Instantiation\n",
        "\n",
        "Now we can instantiate our model object and embed text:\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "id": "9ea7a09b",
      "metadata": {},
      "outputs": [],
      "source": [
        "import { WatsonxEmbeddings } from \"@langchain/community/embeddings/ibm\";\n",
        "\n",
        "const embeddings = new WatsonxEmbeddings({\n",
        "  version: \"YYYY-MM-DD\",\n",
        "  serviceUrl: process.env.API_URL,\n",
        "  projectId: \"<PROJECT_ID>\",\n",
        "  spaceId: \"<SPACE_ID>\",\n",
        "  model: \"<MODEL_ID>\",\n",
        "});"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "ba7f5c8a",
      "metadata": {},
      "source": [
        "Note:\n",
        "\n",
        "- You must provide `spaceId` or `projectId` in order to proceed.\n",
        "- Depending on the region of your provisioned service instance, use correct serviceUrl."
      ]
    },
    {
      "cell_type": "markdown",
      "id": "77d271b6",
      "metadata": {},
      "source": [
        "## Indexing and Retrieval\n",
        "\n",
        "Embedding models are often used in retrieval-augmented generation (RAG) flows, both as part of indexing data as well as later retrieving it. For more detailed instructions, please see our RAG tutorials under the [working with external knowledge tutorials](/docs/tutorials/#working-with-external-knowledge).\n",
        "\n",
        "Below, see how to index and retrieve data using the `embeddings` object we initialized above. In this example, we will index and retrieve a sample document using the demo [`MemoryVectorStore`](/docs/integrations/vectorstores/memory)."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 2,
      "id": "d817716b",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "LangChain is the framework for building context-aware reasoning applications\n"
          ]
        }
      ],
      "source": [
        "// Create a vector store with a sample text\n",
        "import { MemoryVectorStore } from \"langchain/vectorstores/memory\";\n",
        "\n",
        "const text = \"LangChain is the framework for building context-aware reasoning applications\";\n",
        "\n",
        "const vectorstore = await MemoryVectorStore.fromDocuments(\n",
        "  [{ pageContent: text, metadata: {} }],\n",
        "  embeddings,\n",
        ");\n",
        "\n",
        "// Use the vector store as a retriever that returns a single document\n",
        "const retriever = vectorstore.asRetriever(1);\n",
        "\n",
        "// Retrieve the most similar text\n",
        "const retrievedDocuments = await retriever.invoke(\"What is LangChain?\");\n",
        "\n",
        "retrievedDocuments[0].pageContent;"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "e02b9855",
      "metadata": {},
      "source": [
        "## Direct Usage\n",
        "\n",
        "Under the hood, the vectorstore and retriever implementations are calling `embeddings.embedDocument(...)` and `embeddings.embedQuery(...)` to create embeddings for the text(s) used in `fromDocuments` and the retriever's `invoke` operations, respectively.\n",
        "\n",
        "You can directly call these methods to get embeddings for your own use cases.\n",
        "\n",
        "### Embed single texts\n",
        "\n",
        "You can embed queries for search with `embedQuery`. This generates a vector representation specific to the query:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 1,
      "id": "0d2befcd",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "[\n",
            "   -0.017436018,  -0.01469498,\n",
            "   -0.015685871, -0.013543149,\n",
            "  -0.0011519607, -0.008123747,\n",
            "    0.015286108, -0.023845721,\n",
            "    -0.02454774,   0.07235078\n",
            "]\n"
          ]
        }
      ],
      "source": [
        "    const singleVector = await embeddings.embedQuery(text);\n",
        "    singleVector.slice(0, 10);"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "1b5a7d03",
      "metadata": {},
      "source": [
        "### Embed multiple texts\n",
        "\n",
        "You can embed multiple texts for indexing with `embedDocuments`. The internals used for this method may (but do not have to) differ from embedding queries:"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": 11,
      "id": "2f4d6e97",
      "metadata": {},
      "outputs": [
        {
          "name": "stdout",
          "output_type": "stream",
          "text": [
            "[\n",
            "  -0.017436024, -0.014695002,\n",
            "   -0.01568589, -0.013543164,\n",
            "  -0.001151976, -0.008123703,\n",
            "   0.015286064, -0.023845702,\n",
            "  -0.024547677,   0.07235076\n",
            "]\n",
            "[\n",
            "     0.03278884, -0.017893745,\n",
            "  -0.0027520044,  0.016506646,\n",
            "    0.028271576,  -0.01284331,\n",
            "    0.014344065, -0.007968607,\n",
            "    -0.03899479,  0.039327156\n",
            "]\n"
          ]
        }
      ],
      "source": [
        "\n",
        "\n",
        "    const text2 = \"LangGraph is a library for building stateful, multi-actor applications with LLMs\";\n",
        "\n",
        "    const vectors = await embeddings.embedDocuments([text, text2]);\n",
        "   \n",
        "    console.log(vectors[0].slice(0, 10));\n",
        "    console.log(vectors[1].slice(0, 10));\n"
      ]
    },
    {
      "cell_type": "markdown",
      "id": "8938e581",
      "metadata": {},
      "source": [
        "## API reference\n",
        "\n",
        "For detailed documentation of all __module_name__ features and configurations head to the API reference: __api_ref_module__"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "JavaScript (Node.js)",
      "language": "javascript",
      "name": "javascript"
    },
    "language_info": {
      "file_extension": ".js",
      "mimetype": "application/javascript",
      "name": "javascript",
      "version": "20.17.0"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 5
}
